<?php

namespace app\admin\controller;

use app\admin\model\Category;
use think\Controller;
use think\Request;
use think\Validate;
use think\Lang;

class Categories extends Controller
{
    public function index()
    {
        $categories = Category::all();
        return view('Categories/index', compact('categories'));
    }

    /***加载新增分类页面
     * @return \think\response\View
     */
    public function create()
    {
        return view('Categories/create');
    }

    /***保存新增
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function save(Request $request)
    {
        $msg = [
            'name.require' => '名称必须',
            'sort.require' => '名称必须',
            'name.max' => '名称最大为8',
            'sort.number' => '排序必须为数字',

        ];
        $validate = Validate::make([
            'name' => 'require|max:8',
            'sort' => 'require|number'
        ], $msg);


        if (!$validate->check($request->param())) {
//            dump($validate->getError());exit;
            return redirect('create')->with('error', $validate->getError());

        } else {
            Category::create($request->param());

            return redirect('index')->with('success', '新增成功');
//            return redirect('Categories/index')->with('success','成功');
//            $this->success('新增成功', 'Categories/index');
        }


    }

    /***加载编辑页面
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        $category = Category::find($id);
        return view('Categories/edit', compact('category'));
    }

    /***保存编辑内容
     * @param Request $request
     * @param $id
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function update(Request $request, $id)
    {
        $category = Category::find($id);
        $category->allowField(true)->save($request->param(), ['id' => $id]);
        return redirect('Categories/index');
    }

    /***删除
     * @param $id
     * @return \think\response\Redirect
     */
    public function delete($id)
    {
        Category::destroy($id);
        return redirect('Categories/index');
    }


}